<?php

class ComboAddressForm extends sfFormDoctrine {
	
	public function configure() {
		$this->embedForm ( 'new', new EmbeddedAddressForm ( null ) );
		
		$this->widgetSchema ['address_id'] = new sfWidgetFormDoctrineChoice ( array ('model' => 'Address', 'add_empty' => 'neue Adresse', 'table_method' => 'getReusableAddresses' ) );
		
		$this->validatorSchema ['address_id'] = new sfValidatorDoctrineChoice ( array ('model' => 'Address', 'required' => false ) );
		
		if (! is_null ( $this->object ))
			$this->setDefault ( 'address_id', $this->object->getId () );
		
		if($this->getReferenceableForm()) {
			$this->widgetSchema['use_reference'] = new sfWidgetFormInputCheckbox();
			$this->validatorSchema['use_reference'] = new sfValidatorBoolean();
		}
	}
	
	/**
	 * @return ComboAddressForm
	 */
	protected function getReferenceableForm() {
		return $this->getOption('referenceable_form', null);
	}
	
	public function updateObject($values=null) {
		if($this->getReferenceableForm() && $values['use_reference']) {
			$this->object = $this->getReferenceableForm()->getObject();
		} elseif($values['address_id']) {
			unset($this->embeddedForms['new']);
			$this->object = AddressTable::getInstance ()->findOneById ( $values['address_id'] );
		} else {
			$this->object = $this->embeddedForms['new']->getObject();
		}
		$this->object->setReusable(true);
		return parent::updateObject($values);
	}
	
	public function saveEmbeddedForms($con = null, $forms = null) {
		// do nothing
	}
	
	public function getModelName() {
		return 'Address';
	}
}